/**
 * 
 */
package com.hjx.service.system.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.hjx.dao.RoleMapper;
import com.hjx.dao.UserMapper;
import com.hjx.dao.UserRoleMapper;
import com.hjx.model.Role;
import com.hjx.model.RoleCriteria;
import com.hjx.model.User;
import com.hjx.model.UserCriteria;
import com.hjx.model.UserRole;
import com.hjx.model.UserRoleCriteria;

/**
 * @author huangjixin 2012-8-3, 下午2:57:36
 */
public class UserDetailsSerivceImpl implements UserDetailsService {

	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private UserRoleMapper userRoleMapper;
	
	@Autowired
	private RoleMapper roleMapper;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.springframework.security.core.userdetails.UserDetailsService#
	 * loadUserByUsername(java.lang.String)
	 */
	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		UserCriteria userCriteria = new UserCriteria();
		userCriteria.createCriteria().andUsernameEqualTo(username);
		List<User> list = userMapper.selectByExample(userCriteria);

		if (list.size() == 0) {
			throw new UsernameNotFoundException("无此用户!");
		}
		
		User user = (User) list.get(0); 
		List<GrantedAuthority> AUTHORITIES = new ArrayList<GrantedAuthority>();
		
		UserRoleCriteria userRoleCriteria = new UserRoleCriteria();
		userRoleCriteria.createCriteria().andUserIdEqualTo(user.getId());
		List<UserRole>userRoleList = userRoleMapper.selectByExample(userRoleCriteria);
		
		List<Integer> values = new ArrayList<Integer>();
		for (UserRole userRole : userRoleList) {
			values.add(userRole.getRoleId()); 
		}
		
		RoleCriteria roleCriteria = new RoleCriteria();
		
		roleCriteria.createCriteria().andIdIn(values);
		List<Role>roleList = roleMapper.selectByExample(roleCriteria);
		for (Role role : roleList) {
			AUTHORITIES.add(new SimpleGrantedAuthority(role.getName())); 
		}
		
		org.springframework.security.core.userdetails.User userCre = new org.springframework.security.core.userdetails.User(username, user.getPassword(), AUTHORITIES);
		return userCre;
	}

}
